package cn.tedu.ivos.service.impl;

import cn.tedu.ivos.mapper.UserMapper;
import cn.tedu.ivos.pojo.LoginUserParam;
import cn.tedu.ivos.pojo.LoginUserVO;
import cn.tedu.ivos.pojo.LoginUserPrinciple;
import cn.tedu.ivos.service.UserService;
import cn.tedu.ivos.pojo.LoginUser;
import cn.tedu.ivos.utils.JwtUtils;
import cn.tedu.ivos.utils.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public LoginUserVO login(LoginUserParam loginUserParam) {
        String username=loginUserParam.getUsername();
        String password=loginUserParam.getPassword();
        System.out.println(loginUserParam);
        LoginUser sysUser = userMapper.selectByUsername(username);
        if(sysUser==null)
            throw new RuntimeException("用户名或密码不正确");
        if(!PasswordUtils.checkPassword(password,sysUser.getPassword()))
            throw new RuntimeException("用户名或密码不正确");
        //构建用户身份对象
        LoginUserPrinciple userPrinciple=new LoginUserPrinciple();
        userPrinciple.setId(sysUser.getId())
                .setUsername(sysUser.getUsername())
                .setNickname(sysUser.getNickname())
                .setPhone(sysUser.getPhone())
                .setEmail(sysUser.getEmail());
        //创建令牌
        String token= JwtUtils.generateToken(userPrinciple);
        //封装数据
        LoginUserVO loginUserVO=new LoginUserVO();
        loginUserVO.setJwtToken(token)
                .setHeaderName("Authorization")
                .setPrefix("Bearer ");
        return loginUserVO;
    }
}
